/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multiface.web.util;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import multiface.promonet.jpa.Utente;
import multiface.web.util.Define;

/**
 *
 * @author Diego64
 */
public class ServletUtil {

    public static boolean userIsLoggedByType(HttpSession session, String userType) {
        if (session.getAttribute(Define.USER_SESSION) != null) {
            return false;
        } else {
            Utente u = (Utente) session.getAttribute(Define.USER_SESSION);
            if (u.getTipo().equals(userType)) {
                return true;
            }
        }
        return false;
    }

    public static boolean userIsLogged(HttpSession session) {
        if (session.getAttribute(Define.USER_SESSION) == null) {
            return false;
        } else {
            return true;
        }
    }

    public static String getRelativeUrl(HttpServletRequest request) {

        String baseUrl = null;

        if ((request.getServerPort() == 80)
                || (request.getServerPort() == 443)) {
            baseUrl =
                    request.getScheme() + "://"
                    + request.getServerName()
                    + request.getContextPath();
        } else {
            baseUrl =
                    request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath();
        }

        StringBuffer buf = request.getRequestURL();

        if (request.getQueryString() != null) {
            buf.append("?");
            buf.append(request.getQueryString());
        }

        return buf.substring(baseUrl.length());
    }

    /**
     * NOT UNIT TESTED Returns the base url (e.g,
     * <tt>http://myhost:8080/myapp</tt>) suitable for using in a base tag or
     * building reliable urls.
     */
    public static String getBaseUrl(HttpServletRequest request) {
        if ((request.getServerPort() == 80)
                || (request.getServerPort() == 443)) {
            return request.getScheme() + "://"
                    + request.getServerName()
                    + request.getContextPath();
        } else {
            return request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath();
        }
    }

    /**
     * Returns the file specified by <tt>path</tt> as returned by
     * <tt>ServletContext.getRealPath()</tt>.
     */
    public static File getRealFile(HttpServletRequest request, String path) {
        return new File(request.getSession().getServletContext().getRealPath(path));
    }
}
